package com.qdsgjsfk.vision.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.qdsgjsfk.vision.Common;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.eventbus.BlueTooth;
import com.qdsgjsfk.vision.eventbus.Clear;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * Created by HP on 2018/10/8.
 */

public class BlueToothService extends Service {

    public static String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
//    public static String SPP_UUID = "00001105-0000-1000-8000-00805f9B34FB";

    BluetoothAdapter btAdapt = null;
    BluetoothSocket btSocket = null;
    Boolean bConnect = false;
    private InputStream mmInStream;
    private OutputStream mmOutStream;
    String strName = null;
    String strAddress = null;
    String s = "";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        btAdapt = BluetoothAdapter.getDefaultAdapter();
        if (btAdapt == null) {
            Toast.makeText(BlueToothService.this, "本机无蓝牙，连接失败", Toast.LENGTH_SHORT).show();
//            finish();
            return;
        }

        if (btAdapt.getState() != BluetoothAdapter.STATE_ON) {
            Toast.makeText(BlueToothService.this, "本机蓝牙状态不正常，连接失败", Toast.LENGTH_SHORT).show();
//            finish();
            return;
        }
        IntentFilter intent = new IntentFilter();
        intent.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        intent.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

        registerReceiver(connectDevices, intent);
        strName = BaseApplication.strName;
        strAddress = BaseApplication.strAddress;
        mHandler.sendEmptyMessageDelayed(Common.MESSAGE_CONNECT, 1000);
    }


    // Hander
    @SuppressLint("HandlerLeak")
    public final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Common.MESSAGE_CONNECT:
                    new Thread(() -> {
                        InputStream tmpIn;
                        OutputStream tmpOut;
                        try {
                            Log.e("MESSAGE_CONNECT--------", "1111");
                            UUID uuid = UUID.fromString(SPP_UUID);
                            BluetoothDevice btDev = btAdapt
                                    .getRemoteDevice(strAddress);
                            btSocket = btDev.createInsecureRfcommSocketToServiceRecord(uuid);
                            //.createRfcommSocketToServiceRecord(uuid);
                            btSocket.connect();
                            tmpIn = btSocket.getInputStream();
                            tmpOut = btSocket.getOutputStream();
                        } catch (Exception e) {
                            Log.d("CONNECTException---", "Error connected to: "
                                    + strAddress);
                            bConnect = false;
                            mmInStream = null;
                            mmOutStream = null;
                            btSocket = null;
                            e.printStackTrace();
                            mHandler.sendEmptyMessage(Common.MESSAGE_CONNECT_LOST);
                            return;
                        }
                        mmInStream = tmpIn;
                        mmOutStream = tmpOut;
                        mHandler.sendEmptyMessage(Common.MESSAGE_CONNECT_SUCCEED);
                    }).start();
                    break;
                case Common.MESSAGE_CONNECT_SUCCEED:
                    //蓝牙连接成功
                    Toast.makeText(BlueToothService.this, "连接成功", Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().postSticky(new BlueTooth("blueToothService", 200));
                    bConnect = true;
                    new Thread(() -> {
                        byte[] bufRecv = new byte[1024];
                        int nRecv = 0;
                        while (bConnect) {
                            try {
                                nRecv = mmInStream.read(bufRecv);
                                if (nRecv < 1) {
                                    Thread.sleep(100);
                                    continue;
                                }

                                byte[] nPacket = new byte[nRecv];
                                System.arraycopy(bufRecv, 0, nPacket, 0, nRecv);
                                mHandler.obtainMessage(Common.MESSAGE_RECV,
                                        nRecv, -1, nPacket).sendToTarget();
                                Thread.sleep(100);
                            } catch (Exception e) {
                                Log.e(Common.TAG, "Recv thread:" + e.getMessage());
                                mHandler.sendEmptyMessage(Common.MESSAGE_EXCEPTION_RECV);
                                break;
                            }
                        }
                        Log.e(Common.TAG, "Exit while");
                    }).start();
                    break;
                case Common.MESSAGE_EXCEPTION_RECV:
                case Common.MESSAGE_CONNECT_LOST:
                    Toast.makeText(BlueToothService.this, "连接异常，请靠近验光仪重新连接", Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().postSticky(new BlueTooth("blueToothService", 500));
                    try {
                        if (mmInStream != null)
                            mmInStream.close();
                        if (mmOutStream != null)
                            mmOutStream.close();
                        if (btSocket != null)
                            btSocket.close();
                    } catch (IOException e) {
                        Log.e(Common.TAG, "Close Error");
                        e.printStackTrace();
                    } finally {
                        mmInStream = null;
                        mmOutStream = null;
                        btSocket = null;
                        bConnect = false;
                    }
                    break;
                case Common.MESSAGE_WRITE:
                    System.out.println("MESSAGE_WRITE");
                    break;
                case Common.MESSAGE_READ:
                    System.out.println("MESSAGE_READ");
                    break;
                case Common.MESSAGE_RECV:
                    byte[] bBuf = (byte[]) msg.obj;
                    System.out.println(bytesToString(bBuf, msg.arg1));
                    s = s + bytesToString(bBuf, msg.arg1);

                    mHandler.postDelayed(() -> {
                        if (!TextUtils.isEmpty(s)) {
                            Log.e("经典蓝牙数据-----", s);
                            if (getJSONType(s)) {
                                //能解析成json
                                EventBus.getDefault().postSticky(new BlueTooth(s, 110));
                            } else {
                                EventBus.getDefault().postSticky(new BlueTooth(s, 1));
                            }
                        }
                    }, 1000);
//                    addLog("接收数据: " + bytesToString(bBuf, msg.arg1));
                    break;
                case Common.MESSAGE_TOAST:
                    Toast.makeText(BlueToothService.this,
                            msg.getData().getString(Common.TOAST),
                            Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 蓝牙连接状态监听
     *
     * @time 2020/6/4 14:06
     */
    private BroadcastReceiver connectDevices = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(Common.TAG, "Receiver:" + action);
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
                Log.e("蓝牙连接", "onReceive: " + device.getName());//蓝牙的名字
            } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
                Log.e("断开", "onReceive: " + device.getName());//蓝牙的名字
//                btMessage = device.getName() + "蓝牙连接已断开！！";
                //已经断开，开始你的操作，我是用了播放音乐的方式提醒客户，然后在activity里写了一个方法，继续连接。
            }
        }
    };

    @Override
    public void onDestroy() {
        unregisterReceiver(connectDevices);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public static String bytesToString(byte[] b, int length) {
        StringBuffer result = new StringBuffer("");
        for (int i = 0; i < length; i++) {
            result.append((char) (b[i]));
        }

        return result.toString();
    }

    @Subscribe
    public void onMessageEvent(Clear clear) {
        System.out.println("clear");
        s = "";
    }

    public boolean getJSONType(String str) {

        str = str.trim();

        if (str.startsWith("{") && str.endsWith("}")) {

            return true;

        } else if (str.startsWith("[") && str.endsWith("]")) {

            return true;

        }
        return false;

    }


}
